package com.brid.redisTemplate;

import com.alibaba.fastjson.JSON;
import com.brid.careasy.ViolationDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.*;

/**
 * @Author: sijunqiang
 * @Date: 2020/4/21 16:06
 * @Description:
 */
@Slf4j
@Controller
@RequestMapping(value = "/test", produces = MediaType.APPLICATION_JSON_VALUE)
public class RedisController {

    @Autowired
    private RedisConfiguration redisConfiguration;


   private RedisTemplate<String, Object> redisTemplate ;

    /**
     * 测试redis容器
     *
     * @param key
     * @return
     */
    @GetMapping(value = "/redis", consumes = MediaType.APPLICATION_JSON_VALUE)
    public String testRedisTemplate(@RequestParam(value = "key") String key) {
        redisTemplate = redisConfiguration.stringRedisTemplate();
        redisTemplate.opsForValue().set(key, "hello world");
        Object o = redisTemplate.opsForValue().get(key);
        System.out.println("o = " + o);
        return "success";
    }

    public void requestThreeTime() {
        for (int i = 0; i < 3; i++) {
            testSaveThreeTime("66666");
        }
    }

    public void testSaveThreeTime(String key) {
        Object o = redisTemplate.opsForValue().get(key);
        // 1：先去缓存中查询指定key对应的值
        Object value = redisTemplate.opsForValue().get(key);
        Integer num = 0;
        if (value != null) {
            num = (Integer) redisTemplate.opsForValue().get(key);
            if (num <= 3) {
                num++;
                redisTemplate.opsForValue().set(key, num);
                Object o1 = redisTemplate.opsForValue().get(key);
                System.out.println("o1 = " + o1);
            } else {
                log.warn("请求的次数:{}次", num);
            }
        } else {
            redisTemplate.opsForValue().set(key, num);
        }
    }




}
